package com.wsfPro.controllers.Account;

import com.wsfPro.controllers.item.LoginDisplay;
import com.wsfPro.controllers.session.LoginSession_WebSocketSession;
import com.wsfPro.core.dao.LoginDisplayService;
import com.wsfPro.core.login.LoginSession_WebSocketSessionInterface;
import com.wsfPro.util.GoEasyUtil;
import com.wsfPro.util.controllerUtil.JsonResult;
import com.wsfPro.util.jwt.JwtUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController("/login")
public class LoginController {

  private static final Logger logger = Logger.getLogger(LoginController.class);
  @Autowired JwtUtil jwtUtil;

  @Resource(name = "goEasyUtil")
  private GoEasyUtil goEasyUtil;
  //	 @Resource(name = "loginSession_WebSocketSession")
  private LoginSession_WebSocketSessionInterface loginSession_WebSocketSessionInterface =
      LoginSession_WebSocketSession.getSession();

  @Resource(name = "loginDisplayServiceImpl")
  private LoginDisplayService loginDisplayServiceImpl;

  @RequestMapping("/logintest")
  public JsonResult getResult() {
    return JsonResult.putSuccess();
  }

  @RequestMapping("loginPage")
  public String loginPage(HttpServletRequest request) {
    logger.info("msgtest");
    // logger.debug("");
    //    // logger.warn("");
    //    // logger.error("");
    return "login";
  }

  // @ResponseBody
  // @RequestMapping(value = "login", method = RequestMethod.POST)
  // public LoginDisplay login(HttpServletRequest request,
  // @RequestBody LoginDisplay loginDisplay) throws Exception {
  // // 登录成功将用户的id md5码作为url{key}
  // LoginDisplay login = loginDisplayServiceImpl.getLogin(
  // loginDisplay.getNickName(), loginDisplay.getPassWord());
  // if (login != null) {
  // System.out.println(login.getEncryptionId());
  //
  // System.out.println(login.DecryptByDisplay());
  // checkOldSess_saveNewSess(login, request);
  // // 登录成功后设置登陆session和key
  // request.getSession().setAttribute("login", login);
  // request.setAttribute("key", login.getEncryptionId());
  // }
  // return login;
  // }
  // 表单提交无需使用requestBody 如果使用则会报451错
  @RequestMapping(value = "login", method = RequestMethod.POST)
  public String login(
      HttpServletRequest request, HttpServletResponse response, LoginDisplay loginDisplay)
      throws Exception {
    // 登录成功将用户的id md5码作为url{key}
    LoginDisplay login =
        loginDisplayServiceImpl.getLogin(loginDisplay.getNickName(), loginDisplay.getPassWord());

    // MDC.put("n", "login");
    logger.info("com/wsfPro/test");

    if (login != null) {
      checkOldSess_saveNewSess(login, request);
      // 登陆成功则存放此时登陆的sesionID=session
      request.setAttribute("sid", request.getSession().getId());
      request.setAttribute("lid", login.getEncryptionId());
      request.getSession().setAttribute("login", login);
      Map<String, Object> userMap = new HashMap<>();
      userMap.put("userName", login.getNickName());
      String token = jwtUtil.generateToken(userMap);
      response.setHeader("authorization", token);
      //      return "play/play1";
      return "login/login";
    }

    return "login/login";
  }

  // @RequestMapping(value = "/person/login", method = RequestMethod.POST)
  // public @ResponseBody
  // User login(@RequestBody User person) {
  // return person;
  // }
  @ResponseBody
  @RequestMapping(value = "login2", method = RequestMethod.POST)
  public String login2(HttpServletRequest request, @RequestBody LoginDisplay loginDisplay) {
    return "com/wsfPro/test";
  }

  /**
   * 检查是否登录过如果登陆过则对旧的session设置提示有重复登陆
   *
   * @param login
   * @param request
   */
  private void checkOldSess_saveNewSess(LoginDisplay login, HttpServletRequest request) {

    HttpSession oldLoginSession =
        loginSession_WebSocketSessionInterface.getHttpSessionByLid(login.DecryptByDisplay());
    // oldLoginSession不为null则重复登录
    if (oldLoginSession != null) {
      System.out.println(
          "login:"
              + login.getNickName()
              + "nowSessionId:"
              + request.getSession().getId()
              + " oldSessionId:"
              + oldLoginSession.getId());
      // 如果浏览器已经有账号登录成功但是去登录页面重新登录自己账号会生成新的sessionID则这里判断不了session是否为同一个
      if (oldLoginSession.getId().equals(request.getSession().getId())) {
        request.setAttribute("LoginMsg", "您已经登陆,无需重复登陆");
        return;
      } else {
        // login.setMsg1("您已经登陆,无需重复登陆");
        if (oldLoginSession.getAttribute("login") != null) {
          try {
            // WebSocketUtil.httpSessionId_webSocket
            // .get(oldLoginSession.getId()).getBasicRemote()
            // .sendText("1");
            Session webSocketSession =
                loginSession_WebSocketSessionInterface.getWebSocketSessionByLid(
                    login.DecryptByDisplay());
            if (webSocketSession != null) {
              if (webSocketSession.isOpen()) {
                webSocketSession.getBasicRemote().sendText("1");
              }
            }
          } catch (IOException e) {
            e.printStackTrace();
          }
          /**
           * session销毁监听器执行移除集合session主要移除sid— sessionMap因为每个sessionId不一致所以无法用put顶替掉原来的但lid是唯一的则可以
           */
          oldLoginSession.invalidate();
          if (loginSession_WebSocketSessionInterface.getWebSocketSessionByLid(
                  login.DecryptByDisplay())
              != null) {
            try {
              loginSession_WebSocketSessionInterface
                  .getWebSocketSessionByLid(login.DecryptByDisplay())
                  .close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }

          // loginSession_WebSocketSessionInterface
          // .removeLoginSession_WebSocketSession(loginSession_WebSocketSessionInterface
          // .getLoginIdBySession(oldLoginSession));
        }
        // 登录成功后设置登陆session和key
        // session销毁时间
        // request.getSession().setMaxInactiveInterval(20);

        // LoginSessionMap.LOGIN_SESSION.put(login.DecryptByDisplay(),
        // request.getSession());
        // LoginSessionMap.SESSIONID_SESSION.put(request.getSession().getId(),
        // request.getSession());

      }
    }
    loginSession_WebSocketSessionInterface.saveLoginSession(
        login.DecryptByDisplay(), request.getSession());
  }

  @RequestMapping("/mvc1")
  public String mvc1() {
    return "index";
  }

  @RequestMapping("/mvc2")
  @ResponseBody
  public ModelAndView mvc2() {
    ModelAndView mv = new ModelAndView("index.ftl");
    return mv;
  }

  @RequestMapping("/greet")
  public String greeting(
      @RequestParam(value = "name", required = false, defaultValue = "World") String name,
      Model model) {
    LoginDisplay login = null;
    try {
      login = loginDisplayServiceImpl.getLogin("1", "1");
      model.addAttribute("name", login.getNickName());
    } catch (Exception e) {
      e.printStackTrace();
    }

    return "greets";
  }
}
